from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from certificate_manager.serializers import AuthUserSerializer, UserSerializer
from certificate_manager.models import User, UserManager, Department
from rest_framework.exceptions import APIException

from rest_framework.serializers import ValidationError

from json import loads
import requests

def from_user_to_back(user):
    token, created = Token.objects.get_or_create(user=user)
    ret = UserSerializer(user).data
    ret['token'] = token.key
    return Response(ret)


class AuthToken(ObtainAuthToken):
        serializer_class = AuthUserSerializer

        def post(self, request, *args, **kwargs):
                # 我们在这里将请求转到另一个地方，然后尝试查询用户，如果没有就创建。那么老师怎么办? 哈哈 老师肯定存在的
                # 我们应该先查找库中是否存在 如果不存在再通过第三方
                serializer = self.serializer_class(data=request.data, context={'request': request})
                # Why here error? We have no idea.
                try :
                    serializer.is_valid(raise_exception=True)
                    return from_user_to_back(serializer.validated_data)
                except ValidationError as e:
                    # 现在要通过第三方发包了
                    data = {
                        'stuId': request.data['uid'],
                        'stuPass': request.data['password']
                    }

                    try:
                        res = requests.post(url='http://localhost:7002/auth/stu/login', data=data)
                        res = loads(res.text)
                    except:
                        raise APIException(detail='认证失败-后端服务响应异常')

                    if res['status'] == 200:
                        stu_info = res['data']
                        # 我们就要尝试查找，如果没有用户就创建 并返回Token
                        if User.objects.filter(uid=stu_info['xh']):
                            return from_user_to_back(User.objects.get(uid=stu_info['xh']))
                            
                        else:
                            # 现在我们就要创建了。我们只能通过UserManager进行创建，并且返回对象
                            # def create_user(self, uid, password, name, department, telephone="", email="", commit=True):
                            # 现在我们还要查找部分
                            dep = Department.objects.get(name="软件学院")
                            user = User.objects.create_user(uid=stu_info['xh'], password='NUC_FrOm_SSO', name=stu_info['xm'], department=dep, commit=True)
                            return from_user_to_back(user)
                    else:
                        # 登录失败 后端API没结果
                        raise APIException(detail='认证失败-Geexin认证错误且后端认证用户密码错误')
